<?php
/**
 * Created by 老吴.
 * UserMsg:砥砺前行，扬帆起航
 * email:cwwx0128@qq.com
 * QQ:1113249273
 * QQ群:925283872
 * 微信:cww0128
 * Date: 2021/4/15
 * Time: 23:08
 */

namespace app\api\controller;

use addons\third\model\Third;
use app\common\controller\Api;
use Exception;
use fast\Http;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

class Wechat extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $appid;
    protected $secret;
    protected $loginUrl;

    public function __construct()
    {
        $this->appid = 'wx1358fa2c157e0ac0';//get_addon_config("login")['appId'];
        $this->secret = '80442ee4d5d89d3e72eeccab5b101513';//get_addon_config("login")['secretId'];
        $this->loginUrl = "https://api.weixin.qq.com/sns/jscode2session?" . "appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";//get_addon_config("login")['loginUrl'];
        parent::__construct();
    }
    /**
     * desc: 获取小程序用户openid
     */
    public function getOpenid()
    {
        $code = $this->request->post('code');
        $phoneNumber = $this->request->post('phoneNumber');
        $wxUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code';
        $getUrl = sprintf($wxUrl, $this->appid, $this->secret, $code);//把appid，appsecret，code拼接到url里
        $result = $this->http_curl($getUrl);//请求拼接好的url
        $wxResult = json_decode($result, true);

        try {
            if (empty($wxResult)) {
                throw new Exception('获取openid时异常，微信内部错误');
            } else {
                $loginFail = array_key_exists('errcode', $wxResult);
                if ($loginFail) {//请求失败
                    throw new Exception('请求失败');
                }
            }
            $openid = $wxResult['openid'];
            $model = new Third();
            $info = $model->where(['openid' => $openid])->find();
            $nickname = $phoneNumber;
            if ($info) {
                $userMoel = \app\common\model\User::get($info->user_id);
                $userMoel->save([
                    'nickname' => $nickname,
                    'username' =>  rand(0,99999999),//$nickname,
                    'mobile' => $nickname
                ]);
                $this->auth->direct($info->user_id);
            }else {
                $ret = $this->auth->register(rand(0,99999999), '123456', '', $nickname);
                if($ret) {
                    $model->save([
                        'user_id' => $this->auth->id,
                        'platform' => '',
                        'apptype' => 'wxMiniProgram',
                        'openid' => $openid,
                        'openname' => $nickname
                    ]);
                }else {
                    throw new Exception($this->auth->getError());
                }
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $userinfo = $this->auth->getUserinfo();

        if($userinfo) {
            $data = ['userinfo' => $userinfo];
            $this->success(__('Sign up successful'), $data);
        }else{
            $this->error(__('登录失败，请重新授权'));
        }
    }

    //php请求网络的方法
    public  function http_curl($url){
        $curl = curl_init();
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,30);
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        $response=curl_exec($curl);
        curl_close($curl);
        return $response;
    }

    // 获取手机号 和access_token
    public function getWxPhoneNumber()
    {
        $code = $this->request->post('code');
        $token = $this->getWxToken();
        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token;
        $data = json_encode(["code" => $code]);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, true);        // 发送post请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // 传入post参数

        $res = curl_exec($ch);

        curl_close($ch);
        $rest = json_decode($res,true);
        if($rest['errmsg'] == 'ok') {
            $this->success('成功',['phoneNumber' => $rest['phone_info']['phoneNumber']]);
        }else {
            $this->error('失败');
        }
    }
    // 获取access_token
    public function getWxToken()
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->secret;
        $token = json_decode(file_get_contents($url, true), true);
        $token = $token['access_token'];
        return $token;
    }
}